/*!
 * New Target Strategy.
 * Date: 2015/12/31.
 * Copyright© 2014-2015 Vamaker All Rights Reserved.
 */
require([
  'jquery',
	'pageInit',
  'formAjax',
  'notification',
  'dateRange',
  'moment',
  'timeInterval',
  'select2',
  'tree'
], function ($, vamakerPage, formAjax, VamOpMsg, DateRange, moment, TimeInterval, select2, tree) {
  $(function () {
    var $strategyTab = $('#strategy-target-tab'),
    $strategyContent = $('#strategy-target-content');
    $strategyTab.on('click', 'li', function (evt) {
      var $me = $(this),
        currIndex = $strategyTab.children().index($me);
      evt.preventDefault();
      // console.log(currIndex);
      $strategyContent.children().removeClass('active in');
      $strategyContent.children().eq(currIndex).addClass('active in');
    });
  });
  $(function () {
    var $dataFrm = $('#strategy_target_frm'),
      $submitBtn = $dataFrm.find('button[type="submit"]'),
      $operateBtn = $submitBtn.filter('.save-btn'),
      $operateType = $dataFrm.find('.operate-type'),
      strategyName = $('#strategy_name').val();

      $submitBtn.on('click', function (evt) {
        var $me = $(this),
          operate = $me.data('operate'),
          operateTxt;
        operateTxt = '.' + operate + '-btn';
        $operateBtn = $submitBtn.filter(operateTxt);
        $operateType.val(operate);
      });
      $dataFrm.submit(function () {
        var $me = $(this);
        $me.ajaxSubmit({
          beforeSubmit: function() {
            $operateBtn.button('loading');
          },
          success: function (data) {
            var next = $operateBtn.data('operate');
            $operateBtn.button('reset');
            if (data.status === 'success') {
              VamOpMsg.messager(data);
              if (next === 'save-next') {
                window.location.href = VAM.getVar('NEXT_URL') + '?solution_id=' + data.data.id + '&strategy_name=' + strategyName;
              } else {
                window.location.href = 'solution-list';
              };
            } else {
              VamOpMsg.messager(data);
            }
          }
        });
        return false;
      });
  });
  // Time Target
  $(function () {
    var $timeIntervalWrap = $('.time-interval-wrap'),
      timeInterval = new TimeInterval(),
      langVer = VAM.getVar("LANGUAGE"),
      weekdays = ['Mon', 'Tue', 'Wen', 'Thu', 'Fri', 'Sat', 'Sun'],
      weekDayHtml, dayTime='', timeIntervalWrapHtml;
      if (langVer === "zh-CN") {
        weekdays = ['星期一','星期二','星期三','星期四','星期五','星期六','星期日']
      };
      for (var i = 1; i <= weekdays.length; i++) {
        var day, timeUnit;
        if (i===7) {day=0;}else{day=i;};
        weekDayHtml = '<div class=""><label class="checkbox-inline weekdays"><input type="checkbox" id="week_'+ day +'"checked="checked" class="week-ckb work-ckb">'
          + weekdays[i-1] +'</label><div class="btn-group" data-toggle="buttons">';
        for (var j = 0; j < 24; j++) {
          var g;
          if (j<10) {
            g = j + 1;
            if (j === 9) {
              g = '' + g;
            } else {
              g = '0' + g;
            };
            j='0'+j;
            timeUnit = j + ':00-' + g + ':00';
        }else{
          g = j + 1;
          j=''+j;
          timeUnit = j + ':00-' + g + ':00';
        };
          weekTime = day+j;
          dayTime = dayTime+'<label class="btn btn-primary btn-sm" data-container="body" data-toggle="tooltip" data-placement="top" title="'+ timeUnit +'"><input type="checkbox" name="period[]" value="'+ weekTime +'"> &nbsp;&nbsp;&nbsp;</label>';
        };
        timeIntervalWrapHtml = weekDayHtml+dayTime+'</div></div>';
        $('.time-select-wrap').append(timeIntervalWrapHtml);
        dayTime='';
      };
      $('#time-target').find('[data-toggle="tooltip"]').tooltip();
      timeInterval.init($timeIntervalWrap);     
  });
  // Content Target
  $(function () {
    $('#target_content_type').select2({
      allowClear: true
    });
  });
  // IP Target
  $(function () {
    var $ipTargetNumbers = $('.target_ip_number'),
      $targetIpOp = $('#target_ip_op'),
      $targetIpNumberErr = $('#target_ip_number_err'),
      $targetIpFilter = $('#target_ip_filter'),
      $targetIpTable = $('#target_ip_table'),
      $targetIpList = $('#target_ip_list'),
      ipsArr = [],
      ipTableRender,
      ipDeleteRender;
      ipTableRender = function (ips) {
        // console.log(ips);
        var ipArr = ips.split(','),
          $tbody = $targetIpTable.find('tbody'),
          rows = '';
        if (ips === '') {
          ipArr = [];
        }
        $tbody.children().remove();
        for (var i = 0, len = ipArr.length; i < len; i++) {
          if (ipArr[i] === '') {
            continue;
          };
          var row = '';
          row = '<tr><td class="table-ip">' + ipArr[i] + '</td>'
              + '<td><button class="btn btn-danger btn-xs ip-delete" type="button"><i class="fa fa-trash"></i>'+ VAM.j('delete') +'</button></td>'
              + '</tr>';
          rows += row
        };
        if (ipArr.length === 0) {
          rows = '<tr><td class="text-center" colspan="2">' + VAM.j('No record') + '</td></tr>';
        }
        $tbody.html(rows);
      };

      ipDeleteRender = function (ip) {
        var ipsArr = $targetIpList.val().split(',');
        ip = $.trim(ip);
        // console.log(ipsArr);
        for (var i = 0, len = ipsArr.length; i < len; i++) {
          if (ip === ipsArr[i]) {
            ipsArr.splice(i, 1);
            // console.log(ipsArr);
            $targetIpList.val(ipsArr.join(','));
            break;
          };
        };
      };

      $targetIpTable.on('click', '.ip-delete', function(evt) {
        var $me = $(this),
          $row = $me.parents('tr'),
          ip = $row.find('.table-ip').text();
        evt.preventDefault();
        ipDeleteRender(ip);
        $row.remove();
      });

      $ipTargetNumbers.on('blur', function () {
        var $me = $(this),
          meVal = $me.val();
          if (meVal === '') {
            $targetIpNumberErr.html('<em class="checky-default-failure">'+ VAM.j('IP cannot be empty') +'</em>');
          } else if (!/^\d+$/.test(meVal)) {
            $targetIpNumberErr.html('<em class="checky-default-failure">'+ VAM.j('IP can only be number') +'</em>');
          } else if (parseInt(meVal, 10) < 0 || parseInt(meVal, 10) > 256) {
            $targetIpNumberErr.html('<em class="checky-default-failure">'+ VAM.j('IP value can only be between 0 ~ 255') +'</em>');
          } else {
            $targetIpNumberErr.html('');
          };
      });

      $targetIpOp.on('click', function (evt) {
        var $me = $(this);
        $ipTargetNumbers.trigger('blur'),
        ipStartText = '',
        ipEndText = '',
        ipText = '';
        if ($targetIpNumberErr.html() !== '') {
          return;
        };
        for (var i = 0; i < 3; i++) {
          ipStartText += $ipTargetNumbers.eq(i).val() + '.';
        };
        ipStartText += $ipTargetNumbers.eq(3).val();
        for (var j = 4; j < $ipTargetNumbers.length -1; j++) {
          ipEndText += $ipTargetNumbers.eq(j).val() + '.';
        };
        ipEndText += $ipTargetNumbers.eq(j).val();
        ipText = ipStartText + ' - ' + ipEndText;
        
        ipsArr = $targetIpList.val().split(',');
        // console.log(ipsArr);
        ipsArr.push(ipText);
        // console.log(ipsArr);
        $targetIpList.val(ipsArr.join(','));
        // console.log($targetIpList.val());
        ipTableRender($targetIpList.val());

        $ipTargetNumbers.val('');
      });

      // Init Ips Table
      ipTableRender($targetIpList.val());
  });
  // Geo Target
  $(function () {
    var $geoIntervalWrap = $('.geo-interval-wrap'),
    checkedStatus;
    $geoIntervalWrap.on('click', '.geo-eles > label', function(evt) {
      var $me = $(this),
        $subList = $me.parent().siblings('.popover');
      evt.preventDefault();
      $('.popover').hide();
      $subList.show().hover(
        function() {},
        function() {
          $subList.hide();
        });
    });
    checkedStatus = function(checkListLength, checkedListLength, callback) {
      var status = 0;
      if(checkListLength === checkedListLength) {
          //全选状态
          status = 1;
      } else if(checkedListLength === 0) {
          // 一个都没选中
          status = 0;
      } else if(checkListLength >= checkedListLength) {
          // 半选中状态
          status = -1;
      }
      if(callback && typeof callback === 'function') {
          callback(status);
      }
    };
    //顶层控制
    $geoIntervalWrap.on('change', '.ckb-all', function(evt) {
      var $me = $(this),
        $allGeoCkbs = $me.closest('.row').siblings('.row').find('input'),
        $allGeoLabel = $me.closest('.row').siblings('.row').find('label'),
        $geoAll = $('#geo_black_white_all');
      $allGeoCkbs.prop('checked', this.checked);
      $geoAll.prop('checked', this.checked);

      for (var i=0;i<$allGeoLabel.length;i++) {
        $($allGeoLabel[i]).removeClass('half-checked');
      }
      $me.parent().removeClass('half-checked');
    });
    //一层控制
    $geoIntervalWrap.on('change', '.ckb-rank-all', function(evt){
      var $me = $(this),
        myLevLength = $me.parents('.geo-interval-wrap').find('.ckb-rank-all').length,
        myLevChkLength = $me.parents('.geo-interval-wrap').find('.ckb-rank-all:checked').length;
        $subLev = $me.parents('.pd0').siblings('.col-xs-2');

      callback = function(status){
        if (status === 1) {
          $('.ckb-all').prop('checked',true);
          $('.ckb-all').parent().removeClass('half-checked');
        } else if (status === -1){
            $('.ckb-all').prop('checked',false);
            $('.ckb-all').parent().addClass('half-checked');
        } else if (status === 0){
          $('.ckb-all').prop('checked',false);
          if (!!$('.pd0 label').hasClass('half-checked')) {
            $('.ckb-all').parent().removeClass('half-checked');
          };
        }
      };
      $subLev.find('input').prop('checked', this.checked);
      $me.parent().removeClass('half-checked');
      $subLev.find('.geo-eles label').removeClass('half-checked');
      checkedStatus(myLevLength,myLevChkLength,callback); 
    });
    //二层控制
    $geoIntervalWrap.on('change','.geo-eles input', function(evt){
      var $me = $(this),
        $myFather = $me.parents('.rank-two').find('.pd0');
        myLevLength = $myFather.siblings().length;
        myLevChkLength = $myFather.siblings().find('.geo-eles input:checked').length;
        $subLev = $me.parents('.geo-eles').siblings().find('input');
        
      callback = function(status){
        if (status === 1) {
          $myFather.find('input').prop('checked',true);
          $myFather.find('label').removeClass('half-checked');
        }else if (status === -1){ 
          $myFather.find('input').prop('checked',false);
          $myFather.find('label').addClass('half-checked');
        }else if (status === 0){
          $myFather.find('input').prop('checked',false);
          if (!$myFather.siblings().find('.geo-eles label').hasClass('half-checked'))
          {
            $myFather.find('label').removeClass('half-checked');
          }
        }
        //找上层的兄弟层
        myFatherLevLength = $me.parents('.geo-interval-wrap').find('.ckb-rank-all').length;
        myFatherChkLength = $me.parents('.geo-interval-wrap').find('.ckb-rank-all:checked').length;
        checkedStatus(myFatherLevLength,myFatherChkLength,parentCallback);
        $me.siblings('label').removeClass('half-checked');
      };
      parentCallback = function(status){
        if (status === 1) {
          $('.ckb-all').prop('checked',true);
          $('.ckb-all').parent().removeClass('half-checked');
        } else if (status === -1){
            $('.ckb-all').prop('checked',false);
            $('.ckb-all').parent().addClass('half-checked');
        } else if (status === 0){
          $('.ckb-all').prop('checked',false);
          if (!!$('.pd0 label').hasClass('half-checked')) {
            $('.ckb-all').parent().removeClass('half-checked');
          };
        }
      };
      $subLev.prop('checked', this.checked);
      $me.siblings('label').removeClass('half-checked');
      checkedStatus(myLevLength,myLevChkLength,callback);
    });
    //三层控制
    $geoIntervalWrap.on('change','.list-inline input', function(evt){
      var $me = $(this);
        $myFather = $me.parents('.bottom').siblings('.geo-eles');
        $myGrandParent = $me.parents('.rank-two').find('.pd0');
        myLevLength = $me.parents('ul').find('li').length;
        myLevChkLength = $me.parents('ul').find('li input:checked').length;

      callback = function(status){
        if (status === 1) {
          $myFather.find('input').prop('checked',true);
          $myFather.find('label').removeClass('half-checked');
        }else if(status === -1){
          $myFather.find('input').prop('checked',false);
          $myFather.find('label').addClass('half-checked');
          // console.log($myGrandParent);
          $myGrandParent.find('label').addClass('half-checked');
        }else if(status === 0){
          $myFather.find('input').prop('checked',false);
          $myFather.find('label').removeClass('half-checked');
          $myGrandParent.find('label').removeClass('half-checked');
        }
        $myFatherLev = $myGrandParent.siblings();
        myFatherLevLength = $myFatherLev.length;
        myFatherChkLength = $myFatherLev.find('.geo-eles input:checked').length;
        checkedStatus(myFatherLevLength,myFatherChkLength,parentCallback);
      };
      parentCallback = function(status){
        if (status === 1) {
          $myGrandParent.find('input').prop('checked',true);
          $myGrandParent.find('label').removeClass('half-checked');
        }else if(status === -1){
          $myGrandParent.find('input').prop('checked',false);
          $myGrandParent.find('label').addClass('half-checked');
          $('.ckb-all').parents('label').addClass('half-checked');
        }else if(status === 0){
          $myGrandParent.find('input').prop('checked',false);
          //$myGrandParent.find('label').removeClass('half-checked');
        }
        myGrandParentLevLength = $('.ckb-rank-all').length;
        myGrandParentChkLength = $('.ckb-rank-all:checked').length;
        grandPCallback(myGrandParentLevLength,myGrandParentChkLength,grandPCallback);
      };
      grandPCallback = function(status){
        if (status === 1) {
          $('.ckb-all').prop('checked',true);
          $('.ckb-all').parents('label').removeClass('half-checked');
        }else if(status === -1){
          $('.ckb-all').prop('checked',false);
          $('.ckb-all').parents('label').addClass('half-checked');
        }else if (status === 0) {
          $('.ckb-all').prop('checked',false);
          $('.ckb-all').parents('label').removeClass('half-checked');
        }
      };
      checkedStatus(myLevLength, myLevChkLength, callback);
    });
  });
  // Adspace Target
  $(function () {
    $('#target_adspace_type').select2();
  });
  // Brand Target
  $(function () {
    var $brandTargetInput = $('#target_brand_type'),
      $brandTargetErr = $('#target_brand_type_err'),
      $brandAddBtn = $('#brand-add-btn'),
      $targetBrandFilter = $('#target_brand_filter'),
      $targetBrandTable = $('#target_brand_table'),
      $targetBrandList = $('#target_brand_list'),
      brandsArr = [],
      brandTableRender,
      brandpDeleteRender;

      brandTableRender = function (brands) {
        // console.log(ips);
        var brandArr = brands.split(','),
          $tbody = $targetBrandTable.find('tbody'),
          rows = '';
        // console.log(ipArr);
        if (brands === '') {
          brandArr = [];
        }
        $tbody.children().remove();
        for (var i = 0, len = brandArr.length; i < len; i++) {
          if (brandArr[i] === '') {
            continue;
          };
          var row = '';
          row = '<tr><td class="table-brand">' + brandArr[i] + '</td>'
              + '<td><button class="btn btn-danger btn-xs brand-delete" type="button"><i class="fa fa-trash"></i>' + VAM.j('delete') + '</button></td>'
              + '</tr>';
          rows += row
        };
        if (brandArr.length === 0) {
          rows = '<tr><td class="text-center" colspan="2">' + VAM.j('No record') + '</td></tr>';
        }
        // console.log(rows);
        $tbody.html(rows);
      };

      brandDeleteRender = function (brand) {
        var brandsArr = $targetBrandList.val().split(',');
        brand = $.trim(brand);
        // console.log(ipsArr);
        for (var i = 0, len = brandsArr.length; i < len; i++) {
          if (brand === brandsArr[i]) {
            brandsArr.splice(i, 1);
            // console.log(ipsArr);
            $targetBrandList.val(brandsArr.join(','));
            break;
          };
        };
      };

      $targetBrandTable.on('click', '.brand-delete', function(evt) {
        var $me = $(this),
          $row = $me.parents('tr'),
          brand = $row.find('.table-brand').text();
        evt.preventDefault();
        brandDeleteRender(brand);
        $row.remove();
      });

      $brandTargetInput.on('blur', function(evt) {
        var $me = $(this),
          meVal = $me.val(),
          brandUrlReg = /^([a-z0-9]+[a-z0-9\-]*\.){1,2}([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel)$/i;
        evt.preventDefault();
        if (meVal === '') {
          $brandTargetErr.html('<em class="checky-default-failure">' + VAM.j('URL cannot be empty') + '</em>');
        } else if (!brandUrlReg.test(meVal)) {
          $brandTargetErr.html('<em class="checky-default-failure">' + VAM.j('Domain name you entered is illegal, please enter again') + '</em>');
        } else {
          $brandTargetErr.html('');
        };
      });

      $brandAddBtn.on('click', function(evt) {
        evt.preventDefault(),
        brandText = $brandTargetInput.val();
        $brandTargetInput.trigger('blur');
        if ($brandTargetErr.html() !== '') {
          return;
        };
        brandsArr = $targetBrandList.val().split(',');
        // console.log(brandsArr);
        brandsArr.push(brandText);
        // console.log(brandsArr);
        $targetBrandList.val(brandsArr.join(','));
        // console.log($targetIpList.val());
        brandTableRender($targetBrandList.val());
        $brandTargetInput.val('');
      });

      // Init Brands Table
      brandTableRender($targetBrandList.val());
  });
  //Crowd Target
  $(function () {
    var $audienceClass = $('input[name="audience_class"]');
    $audienceClass.on('change',function(){
      var audienceClass = $(this).val();
      $('#crowd-identity').addClass('active in');
      $('#crowd_no_limit').hide();
      switch (audienceClass){
        case '1':
          $('#crowd_own').show();
          $('#crowd_admaster').hide();
          $('#crowd_miaozhen').hide();
          break;
        case '2':
          $('#crowd_miaozhen').show();
          $('#crowd_admaster').hide();
          $('#crowd_own').hide();
          break;
        case '3':
          $('#crowd_admaster').show();
          $('#crowd_miaozhen').hide();
          $('#crowd_own').hide();
          break;
        default:
          $('#crowd_own').hide();
          $('#crowd_admaster').hide();
          $('#crowd_miaozhen').hide();
          break;
      };
    });
    $('input[name="audience_class"]:checked').trigger('change');
  });

  $(function () {
    var $crowdTab = $('.crowd-target-tab a'),
    $crowdContentPane = $('.crowd-target-content').find(' .tab-pane');
    $crowdTab.on('click', function (evt) {
      var $me = $(this),
        target = $me.data('target'),
        targetContent = $me.parents('.nav-tabs').data('target');
      evt.preventDefault();
      $('#' + targetContent).find('.tab-pane').removeClass('in active');
      $('#' + target).addClass('active in');
    });
  });
  $(function () {
    var $crowdIdentiy = $('#crowd-identity'),
      $crowdHobby = $('#crowd-hobby'),
      $crowdTrend = $('#crowd-trend'),
      $identifySelect = $('#identity_select'),
      $hobbySelect = $('#hobby_select'),
      $trendSelect = $('#trend_select'),
      $crowdTargetTab = $('#crowd-target-lab'),
      $crowdTargetId = $('#crowd-target-id'),
      crowdTargetIdArr = [],
      identityData = $.parseJSON(VAM.getVar('IDENTITY_TARGET_DATA')),
      hobbyData = $.parseJSON(VAM.getVar('HOBBY_TARGET_DATA')),
      trendData = $.parseJSON(VAM.getVar('TREND_TARGET_DATA')),
      crowdFilterCallback,
      treeSelectCallback;
      if ($crowdTargetId.val() !== '') {
        crowdTargetIdArr = $crowdTargetId.val().split(',');
      }
      // console.log(crowdTargetIdArr.length);
      crowdFilterCallback = function (subId) {
        crowdTargetIdArr.push(String(subId));
        // console.log(crowdTargetIdArr);
        $crowdTargetId.val(crowdTargetIdArr.join(','));
      };
      treeSelectCallback = function (evt) {
        var 
          node = evt.node,
          nodeTxt = node.name,
          nodeId = String(node.id),
        $selectedTab = $crowdTargetTab.find('option');
        // console.log(nodeId);
        // console.log(crowdTargetIdArr);
        if ($.inArray(nodeId, crowdTargetIdArr) === -1) {
          $crowdTargetTab.append('<option selected value="' + nodeId + '">' + nodeTxt + '</option>');
          crowdFilterCallback(node.id);
        }
        
      }
      $identifySelect.tree({
        data: identityData,
      });
      $hobbySelect.tree({
        data: hobbyData,
      });
      $trendSelect.tree({
        data: trendData,
      });
      var $crowdTargetContent = $('#crowd-target-content');
      $identifySelect.on('tree.click', treeSelectCallback);
      $hobbySelect.on('tree.click', treeSelectCallback);
      $trendSelect.on('tree.click', treeSelectCallback);
      $crowdTargetTab.on('click', 'option', function(){
        var $me = $(this),
          meVal = $me.val();
        crowdTargetIdArr = $.grep(crowdTargetIdArr,function (n, i) {
          // console.log(n);
          if (n == meVal) {
            return false
          } else {
            return true
          }
        });
        // console.log(crowdTargetIdArr);
        $crowdTargetId.val(crowdTargetIdArr.join(','));
        $me.remove();
      })
  });
  //miaozhen Audience Target
  $(function () {
    var $crowdIdentiy = $('#miaozhen-crowd-age'),
      $crowdHobby = $('#miaozhen-crowd-hobby'),
      $ageSelect = $('#miaozhen_age_select'),
      $hobbySelect = $('#miaozhen_hobby_select'),
      $crowdTargetTab = $('#crowd-miaozhen-target-lab'),
      $crowdTargetId = $('#crowd-miaozhen-target-id'),
      crowdTargetIdArr = [],
      ageData = $.parseJSON(VAM.getVar('M_AGE_TARGET_DATA')),
      hobbyData = $.parseJSON(VAM.getVar('M_HOBBY_TARGET_DATA')),
      crowdFilterCallback,
      treeSelectCallback;
      if ($crowdTargetId.val() !== '') {
        crowdTargetIdArr = $crowdTargetId.val().split(',');
      }
      // console.log(crowdTargetIdArr.length);
      crowdFilterCallback = function (subId) {
        crowdTargetIdArr.push(String(subId));
        // console.log(crowdTargetIdArr);
        $crowdTargetId.val(crowdTargetIdArr.join(','));
      };
      treeSelectCallback = function (evt) {
        var 
          node = evt.node,
          nodeTxt = node.name,
          nodeId = String(node.id),
        $selectedTab = $crowdTargetTab.find('option');
        // console.log(nodeId);
        // console.log(crowdTargetIdArr);
        if ($.inArray(nodeId, crowdTargetIdArr) === -1) {
          $crowdTargetTab.append('<option selected value="' + nodeId + '">' + nodeTxt + '</option>');
          crowdFilterCallback(node.id);
        }
        
      }
      $ageSelect.tree({
        data: ageData,
      });
      $hobbySelect.tree({
        data: hobbyData,
      });
      var $crowdTargetContent = $('#crowd-miaozhen-target-content');
      $ageSelect.on('tree.click', treeSelectCallback);
      $hobbySelect.on('tree.click', treeSelectCallback);
      $crowdTargetTab.on('click', 'option', function(){
        var $me = $(this),
          meVal = $me.val();
        crowdTargetIdArr = $.grep(crowdTargetIdArr,function (n, i) {
          // console.log(n);
          if (n == meVal) {
            return false
          } else {
            return true
          }
        });
        // console.log(crowdTargetIdArr);
        $crowdTargetId.val(crowdTargetIdArr.join(','));
        $me.remove();
      })
  });
  // Admaster Audience Target
  $(function () {
    var $crowdPopulation = $('#admaster-crowd-population'),
      $crowdMedia = $('#admaster-crowd-media'),
      $crowdCategory = $('#admaster-crowd-category'),
      $crowdDevices = $('#admaster-crowd-devices'),
      $populationSelect = $('#admaster_population_select'),
      $mediaSelect = $('#admaster_media_select'),
      $categorySelect = $('#admaster_category_select'),
      $devicesSelect = $('#admaster_devices_select'),
      $crowdTargetTab = $('#crowd-admaster-target-lab'),
      $crowdTargetId = $('#crowd-admaster-target-id'),
      crowdTargetIdArr = [],
      populationData = $.parseJSON(VAM.getVar('A_POPULATION_TARGET_DATA')),
      mediaData = $.parseJSON(VAM.getVar('A_MEDIA_TARGET_DATA')),
      categoryData = $.parseJSON(VAM.getVar('A_CATEGORY_TARGET_DATA')),
      devicesData = $.parseJSON(VAM.getVar('A_DEVICES_TARGET_DATA')),
      crowdFilterCallback,
      treeSelectCallback;
      if ($crowdTargetId.val() !== '') {
        crowdTargetIdArr = $crowdTargetId.val().split(',');
      }
      // console.log(crowdTargetIdArr.length);
      crowdFilterCallback = function (subId) {
        crowdTargetIdArr.push(String(subId));
        // console.log(crowdTargetIdArr);
        $crowdTargetId.val(crowdTargetIdArr.join(','));
      };
      treeSelectCallback = function (evt) {
        var 
          node = evt.node,
          nodeTxt = node.name,
          nodeId = String(node.id),
        $selectedTab = $crowdTargetTab.find('option');
        // console.log(nodeId);
        // console.log(crowdTargetIdArr);
        if ($.inArray(nodeId, crowdTargetIdArr) === -1) {
          $crowdTargetTab.append('<option selected value="' + nodeId + '">' + nodeTxt + '</option>');
          crowdFilterCallback(node.id);
        }
        
      }
      $populationSelect.tree({
        data: populationData,
      });
      $mediaSelect.tree({
        data: mediaData,
      });
      $categorySelect.tree({
        data: categoryData,
      });
      $devicesSelect.tree({
        data: devicesData,
      });
      var $crowdTargetContent = $('#crowd-target-content');
      $populationSelect.on('tree.click', treeSelectCallback);
      $mediaSelect.on('tree.click', treeSelectCallback);
      $categorySelect.on('tree.click', treeSelectCallback);
      $devicesSelect.on('tree.click', treeSelectCallback);
      $crowdTargetTab.on('click', 'option', function(){
        var $me = $(this),
          meVal = $me.val();
        crowdTargetIdArr = $.grep(crowdTargetIdArr,function (n, i) {
          // console.log(n);
          if (n == meVal) {
            return false
          } else {
            return true
          }
        });
        // console.log(crowdTargetIdArr);
        $crowdTargetId.val(crowdTargetIdArr.join(','));
        $me.remove();
      })
  });
  // Youku/Tudou Channel Target
$(function() {
  var $strategyTab = $('#strategy-target-tab'),
    $strategyContent = $('#strategy-target-content'), 
    $strategyTargetWrap = $("#strategy_target_hidden_wrap"),
    $newYoutuChannelTarget = $('#new-youtu-channel-target'),
    $youtuChannelTargetTemplate = $strategyTargetWrap.find('.youtu_target_panel'),
    $youtuChannelTargetNav = $youtuChannelTargetTemplate.find('.target_nav').remove(),
    $youtuChannelTargetTab = $youtuChannelTargetTemplate.find('.target_tab_panel').remove(),
    checkAllSwitch;
  checkAllSwitch = function ($all, $checkboxes) {
    $all.on('change', function(evt) {
      var $me = $(this),
        status = this.checked;
      $checkboxes.prop('checked', status);
    });
  };
  $strategyTab.on('click', '.youtu-tab-close', function (evt) {
    var $me = $(this),
      $currLink = $me.parent(),
      $bindBtn = $('#' + $currLink.data('button')),
      $currNav = $me.closest('li'),
      currIndex = $strategyTab.children().index($currNav);
    // console.log($bindBtn);
    $bindBtn.removeClass('disabled');
    // Tab Nav.
    $strategyTab.children().removeClass('active');
    $strategyTab.children().eq(currIndex).remove();
    $strategyTab.children().eq(0).addClass('active');
    // Tab Content.
    $strategyContent.children().removeClass('active in');
    $strategyContent.children('.youtu_tab_panel').remove();
    $strategyContent.children().eq(0).addClass('active in');
  });
  $newYoutuChannelTarget.on('click', function (evt) {
    var $youtuNav = $youtuChannelTargetNav.clone(true),
      $youtuTab = $youtuChannelTargetTab.clone(true),
      currStatus = $newYoutuChannelTarget.data('status');
    evt.preventDefault();
    if (!$newYoutuChannelTarget.hasClass('disabled')) {
      $strategyTab.children().removeClass('active');
      $youtuNav.addClass('active');
      $strategyContent.children().removeClass('active in');
      $youtuTab.addClass('active in');

      $strategyTab.append($youtuNav);
      $strategyContent.append($youtuTab);
      checkAllSwitch($('.youtu_channel_all'), $('.youtu_channel_target_wrap').find('input[type="checkbox"]'));
      $newYoutuChannelTarget.addClass('disabled');
    }
    $newYoutuChannelTarget.blur();
  });
});

  // Letv URL Target
$(function() {
  var $strategyTab = $('#strategy-target-tab'),
    $strategyContent = $('#strategy-target-content'), 
    $strategyTargetWrap = $("#strategy_letv_target_hidden_wrap"),
    $newLetvChannelTarget = $('#new-letv-url-target'),
    $letvChannelTargetTemplate = $strategyTargetWrap.find('.letv_target_panel'),
    $letvChannelTargetNav = $letvChannelTargetTemplate.find('.target_nav').remove(),
    $letvChannelTargetTab = $letvChannelTargetTemplate.find('.target_tab_panel').remove();

  $strategyTab.on('click', '.letv-tab-close', function (evt) {
    var $me = $(this),
      $currLink = $me.parent(),
      $bindBtn = $('#' + $currLink.data('button')),
      $currNav = $me.closest('li'),
      currIndex = $strategyTab.children().index($currNav);
    // console.log($bindBtn);
    $bindBtn.removeClass('disabled');
    // Tab Nav.
    $strategyTab.children().removeClass('active');
    $strategyTab.children().eq(currIndex).remove();
    $strategyTab.children().eq(0).addClass('active');
    // Tab Content.
    $strategyContent.children().removeClass('active in');
    $strategyContent.children('.letv_tab_panel').remove();
    $strategyContent.children().eq(0).addClass('active in');
  });
  $newLetvChannelTarget.on('click', function (evt) {
    var $letvNav = $letvChannelTargetNav.clone(true),
      $letvTab = $letvChannelTargetTab.clone(true),
      currStatus = $newLetvChannelTarget.data('status');
    evt.preventDefault();
    if (!$newLetvChannelTarget.hasClass('disabled')) {
      $strategyTab.children().removeClass('active');
      $letvNav.addClass('active');
      $strategyContent.children().removeClass('active in');
      $letvTab.addClass('active in');

      $strategyTab.append($letvNav);
      $strategyContent.append($letvTab);
      $newLetvChannelTarget.addClass('disabled');
    }
    $newLetvChannelTarget.blur();
  });
});
  // Target CheckAll Switch
  $(function () {
    var checkAllSwitch;
    checkAllSwitch = function ($all, $checkboxes) {
      $all.on('change', function(evt) {
        var $me = $(this),
          status = this.checked;
        $checkboxes.prop('checked', status);
      });
    };
    checkAllSwitch($('#geo_black_white_all'), $('.geo-interval-wrap').find('input[type="checkbox"]'));
    checkAllSwitch($('#system_black_white_all'), $('.system-target-wrap').find('input[type="checkbox"]'));
    checkAllSwitch($('#lang_black_white_all'), $('.lang-target-wrap').find('input[type="checkbox"]'));
    checkAllSwitch($('#crowd_sex_all'), $('input[name="audience.gender[]"]'));
    checkAllSwitch($('#crowd_age_all'), $('input[name="audience.age[]"]'));
    checkAllSwitch($('#crowd_income_all'), $('input[name="audience.income[]"]'));
  });

  // Init Data
  $(function () {
    VAM.fn.initData && VAM.fn.initData($);
  });
});
